package com.lsh.payment.service.dmall;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.lsh.payment.api.model.basevo.ExceptionStatus;
import com.lsh.payment.api.model.dmallpay.DMallNotifyRequest;
import com.lsh.payment.api.model.dmallpay.DMallNotifyRequestParam;
import com.lsh.payment.api.model.dmallpay.DMallNotifyResponse;
import com.lsh.payment.api.service.dmallpay.IDMallPayRestService;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.model.payasync.PayMonitorInterfaceModel;
import com.lsh.payment.core.service.async.PayEventBus;
import com.lsh.payment.core.service.dmallpay.impl.DMallNotifyServiceImpl;
import com.lsh.payment.core.util.DateUtil;
import com.lsh.payment.core.util.HttpParamsUntil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * Created by panxudong
 * Date: 17/11/14
 * 北京链商电子商务有限公司
 * Package com.lsh.payment.service.dmall
 * desc:
 * @author peter
 */
@Service(protocol = "rest")
@Path("dmall")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
public class DmallPayRestService implements IDMallPayRestService {

    private static final Logger logger = LoggerFactory.getLogger(DmallPayRestService.class);

    private static final String CHARSET = "UTF-8";

    @Autowired
    private DMallNotifyServiceImpl dMallNotifyService;

    @Path("notify")
    @POST
    @Override
    public DMallNotifyResponse dMallNotify() {
        DMallNotifyRequest request = new DMallNotifyRequest();
        DMallNotifyResponse dMallNotifyResponse = new DMallNotifyResponse();

        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) RpcContext.getContext().getRequest();
            httpServletRequest.setCharacterEncoding(CHARSET);
            Map<String, String> requestMap = HttpParamsUntil.getParams(httpServletRequest);
            logger.info("多点回调请求参数:" + JSON.toJSONString(requestMap));

            request.setSign(requestMap.get("sign"));
            request.setParam(JSON.parseObject(requestMap.get("param"), DMallNotifyRequestParam.class));
        } catch (UnsupportedEncodingException e) {
            logger.error("多点回调参数异常", e);

            dMallNotifyResponse.setCode(ExceptionStatus.E1002001.getCode());
            dMallNotifyResponse.setMsg(ExceptionStatus.E1002001.getMessage());
            return dMallNotifyResponse;
        }

        long beginTime = System.currentTimeMillis();

        boolean result;
        try {
            result = dMallNotifyService.dMallNotify(request);
            if (result) {
                dMallNotifyResponse.setCode(BusinessConstant.DMALL_NOTIFY_SUCCESS);
                dMallNotifyResponse.setMsg(BusinessConstant.OPERATE_SUCCESS_STRING);
            }
        } catch (BusinessException e) {
            dMallNotifyResponse.setCode(e.getCode());
            dMallNotifyResponse.setMsg(e.getMessage());

            logger.error("业务异常:" + e.getCode() + " " + e.getMessage());
            logger.error(e.getMessage(), e);
        } catch (Exception e) {
            dMallNotifyResponse.setCode(ExceptionStatus.E3001001.getCode());
            dMallNotifyResponse.setMsg(ExceptionStatus.E3001001.getMessage());

            logger.error("服务端异常", e);
        }

        long wasteTime = System.currentTimeMillis() - beginTime;
        logger.info("多点回调接口耗时 {} 毫秒。", wasteTime);

        try {
            String wasteTimeStr = (new StringBuffer(DateUtil.nowStrFormate())).append("[").append(wasteTime).append("]").toString();
            PayMonitorInterfaceModel payMonitorInterfaceModel = new PayMonitorInterfaceModel(request, wasteTimeStr, this.getClass().getSimpleName());

            PayEventBus.post(payMonitorInterfaceModel);
        } catch (Throwable e) {
            logger.error("收集监控信息失败", e);
        }

        return dMallNotifyResponse;
    }

}

